package xyz.xcvu.ma2.module;

import cn.hutool.core.date.DateUtil;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.request.BaseWxPayRequest;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;

import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.core.annotation.MagicModule;
import org.ssssssss.script.annotation.Comment;

import java.util.Date;

@Component
@MagicModule("wxpay")
public class WxPay {

    public WxPayService getPayService(
            @Comment("小程序等的appid") String appId,
            @Comment("微信支付商户号") String mchId,
            @Comment("微信支付商户密钥") String mchKey,
            @Comment("V3加密密钥") String apiV3key,
            @Comment("回调url") String url,
            @Comment("证书路径") String privateCert,
            @Comment("证书私钥路径") String privateKey
    ){
        WxPayConfig payConfig = new WxPayConfig();
        payConfig.setAppId(appId);
        payConfig.setMchId(mchId);
        payConfig.setMchKey(mchKey);
        payConfig.setTradeType("JSAPI");
        payConfig.setApiV3Key(apiV3key);
        payConfig.setNotifyUrl(url);
        payConfig.setPrivateCertPath(privateCert);
        payConfig.setPrivateKeyPath(privateKey);
        WxPayService wxPayService = new WxPayServiceImpl();
        wxPayService.setConfig(payConfig);
        return wxPayService;
    }

    @Comment("生成订单信息")
    public Object creatOrder(
            @Comment("微信支付实例")WxPayService wxPayService,
            @Comment("订单号")String orderNo,
            @Comment("主题")String subject,
            @Comment("金额: 元")String amountMoney,
            @Comment("用户ID")String openId,
            @Comment("用户IP")String userIp
    )throws WxPayException {
            WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
            orderRequest.setBody(subject);
            orderRequest.setOutTradeNo(orderNo);
            orderRequest.setTotalFee(BaseWxPayRequest.yuanToFen(amountMoney));//元转成分
            orderRequest.setOpenid(openId);
            orderRequest.setSpbillCreateIp(userIp);
            Date now = new Date();
            Date afterDate = DateUtil.offsetMinute(now, 10);//10分钟后
            orderRequest.setTimeStart(DateUtil.format(now, "yyyyMMddHHmmss"));
            orderRequest.setTimeExpire(DateUtil.format(afterDate, "yyyyMMddHHmmss"));
            return wxPayService.createOrder(orderRequest);
    }

    @Comment("支付回调")
    public WxPayOrderNotifyResult payNotify(String xmlResult, @Comment("微信支付实例")WxPayService wxPayService) throws Exception{
        return wxPayService.parseOrderNotifyResult(xmlResult);
    }
}
